package com.xiaoyu.client.ui.fragment.mall.goods;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.mall.MallGoodsAdapter;
import com.xiaoyu.client.loader.banner.BannerImageLoader;
import com.xiaoyu.client.model.goods.GoodsDetailBean;
import com.xiaoyu.client.model.goods.GoodsFormatBean.FormatParam;
import com.xiaoyu.client.model.goods.GoodsParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.PhotoViewActivity;
import com.xiaoyu.client.ui.activity.forum.ForumDetailActivity;
import com.xiaoyu.client.ui.activity.mall.GoodsDetailsActivity;
import com.xiaoyu.client.ui.activity.mall.OrderComfirmActivity;
import com.xiaoyu.client.ui.activity.mall.StoreActivity;
import com.xiaoyu.client.ui.dialog.SpecificationDialog;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseFragment;
import com.xiaoyu.commonlib.ui.widget.NestedGridView;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商品详情页中的详情fragment
 */
public class GoodsDetailFragment extends BaseFragment {
    @BindView(R.id.fragment_goods_detail_banner)
    Banner mBanner;//轮播图
    @BindView(R.id.fragment_goods_detail_name)
    TextView goodsName;//商品名称
    @BindView(R.id.fragment_goods_detail_price)
    TextView goodsPrice;//价格
    @BindView(R.id.fragment_goods_detail_freight)
    TextView mFreight;//运费
    @BindView(R.id.fragment_goods_detail_store_img)
    CCircleImageView mStoreImg;//商铺图片
    @BindView(R.id.fragment_goods_detail_store_name)
    TextView mStoreName;//商铺名
    @BindView(R.id.detail_content_txt)
    TextView mContentTxt;//商品文字描述
    @BindView(R.id.detail_img_layout)
    LinearLayout mImgLayout;//商品图片描述容器
    @BindView(R.id.detail_goods_recom_list_container)
    NestedGridView mListContainer;//推荐商品列表容器
    private View mView;

    private MallGoodsAdapter mAdapter;
    private List<String> mBannerList = new ArrayList<>();//轮播图数据
    private List<String> mImgList = new ArrayList<>();//商品图片描述
    private List<GoodsParam> mGoodsList = new ArrayList<>();//推荐商品列表
    private String goodsId;//商品id
    private String storeId;//商家id
    private GoodsDetailBean.DataBean goodsModel;//商品model

    private boolean isCollect;//是否收藏
    @BindView(R.id.fragment_goods_details_collect_img)
    ImageView collectImg;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        goodsId = bundle.getString(ClientConstants.GOODS_ID);
        getGoodsInfo();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_goods_detail, container, false);
            ButterKnife.bind(this, mView);

            initView();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }


    private void initView() {
        //顶部轮播图
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置是否自动轮播（不设置则默认自动）
        mBanner.isAutoPlay(true);
        //设置是否允许手动滑动轮播图
        mBanner.setViewPagerIsScroll(true);
        //设置轮播图片间隔时间（不设置默认为2000）
        mBanner.setDelayTime(2000);
        mBanner.setImageLoader(new BannerImageLoader());
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getActivity(),PhotoViewActivity.class);
                intent.putExtra(ClientConstants.IMAGER_LIST_URL, (Serializable) mBannerList);
                intent.putExtra(ClientConstants.IMAGER_CLICK_POS, position);
                startActivity(intent);
            }
        });

        mBanner.setFocusable(true);
        mBanner.setFocusableInTouchMode(true);
        mBanner.requestFocus();


    }

    /**
     * 选择规格
     */
    @OnClick(R.id.fragment_goods_detail_specification_id)
    public void specificationClick() {
        SpecificationDialog dialog = new SpecificationDialog(getActivity(), true, true);
        dialog.initData(goodsModel);
        dialog.show();
    }

    /**
     * 商铺item
     */
    @OnClick({R.id.fragment_goods_detail_store_item, R.id.fragment_goods_detail_store_btn})
    public void itemStoreClick() {
        Intent intent = new Intent(getActivity(), StoreActivity.class);
        intent.putExtra(ClientConstants.STORE_ID, storeId);
        startActivity(intent);
    }

    /**
     * 收藏按钮
     */
    @OnClick(R.id.fragment_goods_detail_collect_btn)
    public void isCollectClick() {
        toCollect();
    }



    /**
     * 立即购买按钮
     */
    @OnClick(R.id.fragment_goods_detail_buy_now_btn)
    public void buyNowClick() {
        SpecificationDialog dialog = new SpecificationDialog(getActivity(), true, true);
        dialog.initData(goodsModel);
        dialog.show();
    }


    /**
     * 产品列表item点击监听
     */
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
            intent.putExtra(ClientConstants.GOODS_ID, mGoodsList.get(position).getGoodsid());
            startActivity(intent);
            getActivity().finish();
        }
    };


    /**
     * 获取商品信息
     */
    private void getGoodsInfo() {
        NetworkManager.getGoodsDetailInfo(goodsId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseGoodsInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("商品详情",errorCode,errorDiscription);
            }
        });
    }

    private void parseGoodsInfoSuc(String result) {
        ToastUtil.logResult("商品详情", result);
        GoodsDetailBean bean = new Gson().fromJson(result, GoodsDetailBean.class);
        goodsModel = bean.getData();
        //轮播图
        mBannerList.clear();
        mBannerList.addAll(bean.getData().getGoodslbimg());
        mBanner.setImages(mBannerList);
        mBanner.start();
        //商品
        goodsName.setText(bean.getData().getGoodsname());//名称
        goodsPrice.setText("¥" + bean.getData().getMinmoney() + "-" + bean.getData().getMaxmoney());//价格区间
        mFreight.setText(bean.getData().getGoodsfreight());//运费
        Glide.with(this).load(bean.getData().getStore().getStoreimg()).into(mStoreImg);//店铺头像
        mStoreName.setText(bean.getData().getStore().getStorename());//店铺名称
        isCollect = bean.getData().isCollect();
        if (bean.getData().isCollect()) {//已收藏
            collectImg.setImageResource(R.drawable.icon_shoucang_pressed);
        } else {
            collectImg.setImageResource(R.drawable.icon_shoucang_normal);
        }

        //文字描述
        mContentTxt.setText(bean.getData().getGoodscontent());
        //图片描述
        mImgList.clear();
        mImgList.addAll(bean.getData().getGoodsxqimg());
        for (int i = 0; i < mImgList.size(); i++) {
            ImageView view = new ImageView(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(params);
            Glide.with(getActivity()).load(mImgList.get(i)).into(view);
            mImgLayout.addView(view, i);
        }
        //产品推荐
        mGoodsList.clear();
        mGoodsList.addAll(bean.getData().getRecommend());
        mAdapter = new MallGoodsAdapter(getActivity(), mGoodsList);
        mListContainer.setAdapter(mAdapter);
        mListContainer.setOnItemClickListener(onItemClickListener);

        storeId = bean.getData().getStore().getGoodsstroreid();

    }



    /**
     * 商品收藏
     */
    private void toCollect() {
        NetworkManager.getGoodsCollect(goodsId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                if (isCollect) {//已收藏
                    isCollect = false;
                    collectImg.setImageResource(R.drawable.icon_shoucang_normal);
                } else {
                    isCollect = true;
                    collectImg.setImageResource(R.drawable.icon_shoucang_pressed);
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

}
